package com.summerlabs.nfc.ui

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.summerlabs.nfc.databinding.ActivityNfcWriteBinding
import com.summerlabs.nfc.utils.NfcUtils
import com.summerlabs.nfc.utils.ToastUtils.showShort
import com.summerlabs.nfc.utils.WLog
import kotlin.concurrent.thread

class NfcWriteActivity : AppCompatActivity() {
    private lateinit var binding: ActivityNfcWriteBinding
    lateinit var nfcUtils: NfcUtils
    var isNdef = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityNfcWriteBinding.inflate(layoutInflater)
        setContentView(binding.root)
        nfcUtils = NfcUtils(this)
        binding.nfcWrite.setOnClickListener {
            mIntent?.let {
                binding.nfcWriteEt.text.toString().takeIf { !it.isBlank() }?.let { msg ->
                    if (isNdef) {
                        nfcUtils.writeNFCToTag(msg, mIntent)
                    } else {
                        nfcUtils.writeMifareClassic(msg, mIntent)
                    }
                }
            }
        }
        binding.ndefCheckBox.setOnCheckedChangeListener { _, isChecked ->
            isNdef = isChecked
        }
    }

    var mIntent: Intent? = null
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        mIntent = intent
    }

    override fun onResume() {
        super.onResume()
        WLog.i("onResume")
        nfcUtils.enableForegroundDispatch()
    }

    fun runIo(block: () -> Unit) {
        thread { block.invoke() }
    }

    override fun onPause() {
        super.onPause()
        WLog.i("onPause")
        nfcUtils.disableForegroundDispatch()
    }
}